#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <pthread.h>
#include <thread>

//int shared_value = 100;
// 线程局部存储
// __thread只能修饰内置类型
 __thread int shared_value = 100;

std::string toHex(pthread_t tid)
{
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "0x%lx", tid);
    return buffer;
}

void *start(void *args)
{
    std::string name = static_cast<const char *>(args);

    while (true)
    {
        printf("I am a new thread, name: %s, shread_value: %d, &shread_value: %p\n", name.c_str(), shared_value, &shared_value);
        sleep(1);
    }

    return nullptr;
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, start, (void *)"thread-1");
    std::cout << "I am a new thread, name : main, " << toHex(pthread_self())
              << " ,NEW thread id : " << toHex(tid) << std::endl;

    while (true)
    {
        printf("main thread, name, shread_value: %d, &shread_value: %p\n", shared_value, &shared_value);
        shared_value += 10;
        sleep(1);
    }

    pthread_join(tid, nullptr);
    return 0;
}
